package com.giveu.signature.common.util;

import java.util.List;

import com.giveu.common.utils.HttpKit;
import com.giveu.signature.common.bean.BaseModel;

import tk.mybatis.mapper.common.BaseMapper;

public class MapperUtil {
	
	@SuppressWarnings("unchecked")
	public  static <E> Long mergeOrder(BaseMapper<E> mapper,E s,BaseModel obj){
		obj.setUpdateIp(HttpKit.getLocalIp());
		BaseModel db = (BaseModel) get(mapper,s);
		if(db==null||db.getId()==null){
			mapper.insertSelective((E) obj);
		}else{
			obj.setId(db.getId());
			mapper.updateByPrimaryKeySelective((E) obj);
		}
		return obj.getId();
	}

	
	@SuppressWarnings("unchecked")
	public  static <E> Long insertOrUpdate(BaseMapper<E> mapper,E q,BaseModel obj){
		obj.setUpdateIp(HttpKit.getLocalIp());
		BaseModel db = (BaseModel) get(mapper,q);
		if(db==null||db.getId()==null){
			mapper.insertSelective((E) obj);
		}else{
			obj.setId(db.getId());
			mapper.updateByPrimaryKeySelective((E) obj);
		}
		return obj.getId();
	}
	
	@SuppressWarnings("unchecked")
	public  static Long insertOrUpdate(BaseMapper mapper,BaseModel obj){
		obj.setUpdateIp(HttpKit.getLocalIp());
		if(mapper.updateByPrimaryKeySelective(obj)==0){
			mapper.insertSelective(obj);
		}
		return obj.getId();
	}
	
	public static <E> E get(BaseMapper<E> mapper,E s){
		List<E> list = mapper.select(s);
		if(list==null||list.isEmpty()){
			return null;
		}
		return list.get(0);
	}

}
